package com.gxc.webcore.util;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

public class RequestUtil {

	/**
	 * 将request中的参数填入到Map对象中
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map getInMap(HttpServletRequest request) {
		Map map = new HashMap();
		Enumeration params = request.getParameterNames();
		while (params.hasMoreElements()) {
			String paramName = (String) params.nextElement();
			String paramValue = request.getParameter(paramName);
			if (paramName.trim().length() > 0) {
				map.put(paramName.trim(), paramValue);
			}
		}
		return map;
	}

	/**
	 * 将request中的参数填入到beanClass类型中
	 * 
	 * @param request
	 * @param beanClass
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	@SuppressWarnings("rawtypes")
	public static Object getInObject(HttpServletRequest request, Class beanClass)
			throws InstantiationException, IllegalAccessException {
		Object objInstance = beanClass.newInstance();
		return getInObject(request, objInstance);
	}

	/**
	 * 将request中的参数填入到object中
	 * 
	 * @param request
	 * @param object
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	@SuppressWarnings("rawtypes")
	public static Object getInObject(HttpServletRequest request, Object object)
			throws InstantiationException, IllegalAccessException {
		BeanWrapper beanWrapper = new BeanWrapperImpl(object);
		Enumeration params = request.getParameterNames();
		while (params.hasMoreElements()) {
			String paramName = ((String) params.nextElement()).trim();
			String paramValue = request.getParameter(paramName);
			if (paramName.trim().length() > 0) {
				// object的可写属性
				if (beanWrapper.isWritableProperty(paramName)) {
					Class<?> clazz = beanWrapper.getPropertyType(paramName);
					// 从请求中查询参数,并转换为相应的类型
					Object value = ConvertUtil.string2Object(clazz, paramValue);
					// 写入属性值
					beanWrapper.setPropertyValue(paramName, value);
				}
			}
		}
		return object;
	}

	/**
	 * 获取请求url，已去掉开头的"/"
	 * 
	 * @param request
	 * @return
	 */
	public static String getUrl(HttpServletRequest request) {
		String url = request.getPathInfo() == null ? request.getServletPath()
				: request.getPathInfo();
		url = url.trim();
		while (url.startsWith("/")) {
			url = url.substring(1);
		}
		return url;
	}

}
